package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.utils.thread.WeMediaThreadLocalUnit;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@Service
@Slf4j
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 上传素材图片
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult upload(MultipartFile multipartFile) {

        //1、参数校验
        if (multipartFile.isEmpty()) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2、数据处理
        //2.1、处理文件名
        String fileName = UUID.randomUUID().toString().replace("-", "");//去掉-
        //2.2、获取原始文件的后缀名
        String originalFilename = multipartFile.getOriginalFilename();
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //3、将图片上传到minIO
        WmMaterial wmMaterial = null;
        String path = null;
        try {
             path = fileStorageService.uploadImgFile("", fileName + postfix, multipartFile.getInputStream());
            //4、封装素材实体对象，并存入数据库表，vm_material
            wmMaterial = WmMaterial.builder()
                    .userId(WeMediaThreadLocalUnit.get())
                    .url(path)
                    .isCollection((short) 0)
                    .type((short) 0)
                    .createdTime(new Date()).build();

            save(wmMaterial);
            log.info("图片上传minIO成功，fileId:{}", path);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("图片上传minIO失败");
        }
        // 5、返回对象（前端才能显示）
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 展示素材列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //1、参数校验
        if (dto == null) throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);//可以不要
        dto.checkParam();//校验分页参数
        //2、分页查询
        LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.<WmMaterial>lambdaQuery()
                //2.1、是否收藏
                .eq(dto.getIsCollection() != null && dto.getIsCollection() == 1,
                        WmMaterial::getIsCollection, dto.getIsCollection())
                //2.2、按照用户查询
                .eq(WmMaterial::getUserId, WeMediaThreadLocalUnit.get());
        //2.3、按照时间倒序
        wrapper.orderByDesc(WmMaterial::getCreatedTime);

        //2.4、查询
        IPage page = new Page(dto.getPage(), dto.getSize());
        page(page, wrapper);
        //3、结果返回
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        result.setCode(AppHttpCodeEnum.SUCCESS.getCode());//设置状态码
        result.setErrorMessage(AppHttpCodeEnum.SUCCESS.getErrorMessage());//设置错误信息（没必要）
        return result;
    }

    /**
     * 删除素材
     *
     * @param id
     */
    @Override
    public void delete(Integer id) {
        baseMapper.deleteById(id);
    }

    /**
     * 收藏素材或取消
     *
     * @param id
     */
    @Override
    public void collection(Integer id) {
        //1、获取到素材对象
        WmMaterial wmMaterial = getById(id);
        // 1.5、判断
        if (wmMaterial.getIsCollection() == 1)
            // 取消收藏
            wmMaterial.setIsCollection((short) 0);
        else
            //2、收藏
            wmMaterial.setIsCollection((short) 1);
        //3、存入wm_Material
        updateById(wmMaterial);
    }
}
